﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BLL;
using DAL;
using ExpressManagement.Areas.BackSys.ServiceTools;
using DAL.Models;
using  static Newtonsoft.Json.JsonConvert;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using Microsoft.Extensions.Caching.Memory;
using BLL.Interface;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.EntityFrameworkCore;
using DAL.Models.DTO;
using MqTools;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
    public class DeliverymanController :  BaseController
    {
        // GET: Deliveryman
        private readonly IDeliverymanImpl _impl;
        //
        // GET: /BackSys/Deliveryman/

        public DeliverymanController(IDeliverymanImpl _impl,IMemoryCache _memoryCache,RedisHelper redisHelper, ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions, IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)

        {
            //if (_impl == null) _impl = new DeliverymanImpl();

            this._impl = _impl;
           
        }
        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> Index()
        {
            return PartialView(_impl.GetList());
        }

        public async Task<IActionResult> DeliverymanRegister()
        {
            return PartialView();
        }

        public async Task<IActionResult> Profile()
        {
            return PartialView();
        }


        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> ChangePage([FromQuery] int page)
        {

            string keyStr = string.Empty;
            string cache = string.Empty;
            string serializeStr = string.Empty;
            IDictionary<string, string> set = new Dictionary<string, string>();
            int? rows = GetInt32FromSession("deliverymanRows");
            if(page!=null)
            SetInt32InSession("deliverymanPage", page);

            cache = GetCacheFromRedis<string>(EntityDeliveryman, TypePage, page, LoginType);
            if (cache!=null)
            {
                return Json(cache);
            }
            else
            {
                switch (LoginType)
                {
                    case "用户":
                    case "快递员":
                        return RedirectToAction("Index", "Home");
                    case "管理员":
                        (var totalPages, var data) = _impl.GetList(rows.Value, page);
                        FillSetAndSaveCache(totalPages, SerializeObject(data), page, set, EntityDeliveryman, TypePage, LoginType, out serializeStr);
                        return Json(serializeStr);
                    default:
                        break;
                }
            }

           

            return Json(0);
        }



        public async Task<IActionResult> DeliverymanManage()
        {

         
                switch (LoginType)
                {
                    case "用户":
                        return RedirectToAction("Index", "Home");
                    case "快递员":
                    case "管理员":
                    //(var totalPages, var data) = _impl.GetList(Convert.ToInt16(MySession.GetSession("deliverymanRows")), Convert.ToInt16(MySession.GetSession("deliverymanPage")));
                    //MySession.WriteSession("deliverymanTotalPages", totalPages);
                    //ViewBag.DeliverymanList = data;
                        return PartialView();
                    default:
                        break;
                }
           
            return PartialView();
        }
        public IActionResult DeliverymanUpdate()
        {
            return PartialView();
        }
        [HttpPost]
        public async Task<IActionResult> Update([FromForm] DeliveryDTO entity)
        {
            //int id = Convert.ToInt32(Request.Form["ID"]);
            //int page = GetInt32FromSession(" deliverymanPage").Value;
           
            if (_impl.Find(entity.Id) == null)
            {
                return Json(0);
            }
            Deliveryman deliveryman = _mapper.Map<Deliveryman>(entity);
            //deliveryman.UserName = Request.Form["UserName"];
            //deliveryman.UserPass = Request.Form["UserPass"];
            //deliveryman.Phone = Request.Form["Phone"];
            //deliveryman.TrueName = Request.Form["TrueName"];
            //deliveryman.Idcard = Request.Form["Idcard"];
            deliveryman.UpdateTime = DateTime.Now;

            if (_impl.Update(entity.Id, deliveryman))
            {
                RemoveRedisCacheEntity(EntityDeliveryman, TypePage, LoginType);
                return Json(1);
            }

                return Json(0);
        }

        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> GetItemByID([FromQuery]string id,[FromQuery]string action)
        {
            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;
            var result = _impl.GetItemByID(Convert.ToInt32(id));
            string seri = SerializeObject(result);
            return Json(seri);
        }

        //
        // POST: /BackSys/Deliveryman/Create
        [HttpPost]
        public async Task< IActionResult> Add([FromForm] DeliveryDTO entity)
        {
            Deliveryman deliveryman =  _mapper.Map<Deliveryman> (entity);
            //deliveryman.UserName = Request.Form["UserName"];
            //deliveryman.UserPass = Request.Form["UserPass"];
            //deliveryman.Phone = Request.Form["Phone"];
            //deliveryman.TrueName = Request.Form["TrueName"];
            //deliveryman.Idcard = Request.Form["Idcard"];
            deliveryman.AddTime = DateTime.Now;
            if (_impl.Add(deliveryman) == true)
            {
                RemoveRedisCacheEntity(EntityDeliveryman, TypePage, LoginType);
                return Json(1);
            }
          
            return Json(0);
        }




        //
        // GET: /BackSys/Deliveryman/Delete/5
        [HttpPost]
        public async Task<IActionResult> Delete(string id, string action)
        {
            //Deliveryman deliveryman = db.Deliverymen.Select(o=>o.Phone=="158888888");
            if (_impl.Delete(Convert.ToInt32(id)) == true)
            {
                RemoveRedisCacheEntity(EntityDeliveryman, TypePage, LoginType);
                return Json(1);
            }

            return Json(0);
        }




    }
}